package com.topdt.jbpm.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.Logger;

public class CalendarUtil {
	
	private static Logger log = Logger.getLogger(CalendarUtil.class);
	
    /**
     * 判断给定的字符串时间是否是和“yyyy-mm-dd”或者“yyyy-m-d”匹配的合法的日期，合法返回true，否则返回false
     * 
     * @param s
     * @return
     */
    public static boolean checkDateFormat(String s) {
        java.util.Date d;
        String format = "yyyy";
        String formatM = null;
        String formatD = null;
        try {
            d = DateFormat.getDateInstance().parse(s);
            String str = null;
            SimpleDateFormat sdFormat = null;
            if (s.substring(s.indexOf("-"), s.lastIndexOf("-")).length() == 3)
                formatM = "-MM";
            else
                formatM = "-M";
            if (s.substring(s.lastIndexOf("-")).length() == 3)
                formatD = "-dd";
            else
                formatD = "-d";
            format = format + formatM + formatD;
            sdFormat = new SimpleDateFormat(format);
            str = sdFormat.format(d);
            if (s.equals(str))
                return true;
            else
                return false;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 返回当前时间所在本年度的周次
     * 
     * @return
     */
    public static int getCurrentWeekOfYear() {
        Calendar calendar = Calendar.getInstance();
        int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
        return weekOfYear;
    }

    /**
     * 返回当前年
     * 
     * @return
     */
    public static int getYear() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        return year;
    }

    /**
     * 将时间date以format格式的字符类型返回
     * 
     * @param date
     * @param format
     * @return
     */
    public static String formatTime(Date date, String format) {
        SimpleDateFormat dateformat = new SimpleDateFormat(format);
        String dates = dateformat.format(date);
        return dates;
    }
    
    /**
     * 将String 转换成 Date类型
     * @param date
     * @param format
     * @return Date
     */
    public static Date formatTime(String date, String format){
    	SimpleDateFormat dateformat = new SimpleDateFormat(format);
    	Date dates = null;
		try {
			dates = dateformat.parse(date);
		} catch (ParseException e) {
			log.warn(" String Conversion date error");
		}
    	return dates;
    }

}
